﻿using Common.Log;
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RealService
{
    public static class HubServer
    {
        //链接SignalR服务地址
        static string ServerUrl = ConfigurationManager.AppSettings["SignalRServerHost"];
        //连接器
        static HubConnection Connection;
        //定义多个集线器（具体要看SignalR服务那边的定义）
        static IHubProxy RealDataHubProxy;
        static HubServer()
        {
            Connection = new HubConnection(ServerUrl);//初始化集线器连接类     
            Connection.Closed += MonitorConnection_Closed;
            Connection.Error += MonitorConnection_Error;
        }
        /// <summary>
        /// 启动连接
        /// </summary>
        static void Start()
        {
            var init = Connection.Start().ContinueWith<bool>(task =>
            {
                //若连接失败，记录日志
                if (task.IsFaulted)
                {
                    foreach (var e in
                             task.Exception.Flatten().InnerExceptions)
                        LogHelper.WriteWarnLog(e.Message + "----------------------------");
                    return false;
                }
                return true;
            });
            //利用Task.Result的同步化等待，待连接完成后再执行下一步
            if (!init.Result)
                Start();
        }
        static void MonitorConnection_Closed()
        {
            Connection.Dispose();
        }

        static void MonitorConnection_Error(Exception obj)
        {
            if (Connection.State == ConnectionState.Disconnected) Start();
            LogHelper.WriteErrorLog(obj.Message + "----------------------------");
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="HubName">集线器名称</param>
        static void InitHubProxy(string hubName)
        {
            if (RealDataHubProxy == null)
                RealDataHubProxy = Connection.CreateHubProxy(hubName);//创建监测点实时数据集线器客户端代理 
            Start();//连接   
        }


        /// <summary>
        /// 订阅方法
        /// </summary>
        /// <param name="HubName">集线器方法名（注意大小写）</param>
        public static void HubSubMsg<T>(string hubName, string hubMethod, Action<T> handlerAction) where T : class
        {
            InitHubProxy(hubName);
            RealDataHubProxy.On<T>(hubMethod, handlerAction); //订阅接收消息
        }
        /// <summary>
        /// 发送数据到指定方法
        /// </summary>
        /// <param name="HubMethod">集线器中的方法名称</param>
        /// <param name="testRealData">参数（可多个）</param>
        public static void SendRealTimeData(string hubName, string hubMethod, params object[] testRealData)
        {
            InitHubProxy(hubName);
            RealDataHubProxy.Invoke(hubMethod, testRealData);
        }
    }
}
